var track_mask_flag = false;

//引入 css 文件
function include_css(path)
{
    var fileref=document.createElement("link");
    fileref.rel = "stylesheet";
    fileref.type = "text/css";
    fileref.href = path;
    document.getElementsByTagName('head')[0].appendChild(fileref);

}


function include_JS(id,newJS)
{
        var oldjs = null;
        var t = null;
        var oldjs = document.getElementById(id);
    if(oldjs){
             oldjs.parentNode.removeChild(oldjs);
    }
        var scriptObj = document.createElement("script");
        scriptObj.src = newJS;
        scriptObj.type = "text/javascript";
        scriptObj.id   = id;
        document.getElementsByTagName("head")[0].appendChild(scriptObj);
}


//重试加载我的终端
function uBandTerminal_comm(){
	if(isConnected){
	    $("#uBandTerminal_comm_id").hide();
	    if(!uBandTerminal_flag){
		sendCmd({
		    c : "uBandTerminal",
		    id : localStorage.getItem("loginUser").split(",")[0],
		    type : 5
		});
		uBandTerminal_flag = true;
		 Device.showMask_blockUI();
		 overTimeCallback_time_2("deviceList","uBandTerminal_comm_id",10000);
	    }
	}else{
				popuo("连接超时，请检查网络设置");
				socket.connect();
		}

}

//重试加载围栏列表
function fencesetting_comm(){
	if(isConnected){
	    $("#fencesetting_comm_id").hide();
		sendCmd({
            c : "fencesetting",
            imei : localStorage.getItem("device").split(",")[0],
            type : 1
        });
		 Device.showMask_blockUI();
		 overTimeCallback_time_2("circleList","fencesetting_comm_id",10000);
	}else{
				popuo("连接超时，请检查网络设置");
				socket.connect();
	}

}

// 回我的终端
function backToMain() {
    // 跨view跳转bug修复

        $("#deviceView").find(".panel").removeClass('active');
        // 进入我的终端界面
        $.afui.loadContent("#main", false, false, "none");
        $("#main").trigger('panelload');
    // var panelObj = $("#deviceView").find(".panel");
    // if (panelObj.length>0){
    //     panelObj.removeClass("active");
    //  }
}

// 日期格式化
function formatDate(o) {
    var time = o.getYear() + 1900;
    //var time = o.getYear() + 1900;
    if (time > 2100) {
        time -= 1900;
    } else {
        time += 0;
    }
    time += '-';
    time += o.getMonth() < 9 ? '0' + (o.getMonth() + 1) : o.getMonth() + 1;
    time += '-';
    time += o.getDate() < 10 ? '0' + o.getDate() : o.getDate();
    time += ' ';
    time += o.getHours() < 10 ? '0' + o.getHours() : o.getHours();
    time += ':';
    time += o.getMinutes() < 10 ? '0' + o.getMinutes() : o.getMinutes();
    time += ':';
    time += o.getSeconds() < 10 ? '0' + o.getSeconds() : o.getSeconds();
    return time;
}

// 创建信息窗体
function createWindow(addr, lng, lat, created, bat) {
    var addrDiv = "spanAddr";
    if (bat == undefined)
        addrDiv = "spanAddr2";
    var html = "<ul style='margin-top: 10px; font-size:11px;'>";
    if (bat != undefined)
        html += "		<li style='height: 24px;'>状态: &nbsp;" + (bat == 0 ? "离线" : "在线") + "&nbsp;&nbsp;&nbsp;电量: &nbsp;" + bat + "%</li>";
    html += "		<li style='height: 24px;'>经纬度: &nbsp;" + Math.round(lng * 1000000) / 1000000 + "，" + Math.round(lat * 1000000) / 1000000 + "</li>";
    html += "		<li style='height: 24px;'>到达时间: &nbsp;" + created + "</li>";
    html += "		<li style='height: 24px;'>地址: &nbsp;<span id='" + addrDiv + "'>" + addr + "</span></li>";
    html += "	</ul>";
    console.log("时间:" + created + "地址:" + addr);
    var opts = {
        width : 140,
        height : bat != undefined ? 145 : 120
        //height : bat != undefined ? 120 : 100,
    }
    if (bat == undefined)
        infoWindow2 = new BMap.InfoWindow(html, opts);
    else
        infoWindow = new BMap.InfoWindow(html, opts);
}

function openWindow(e) {
    var point;
    for (var i = 0; i < points.length; i++) {
        point = points[i];
        var lngLength = ("" + e.target.getPosition().lng).length - 1 - ("" + e.target.getPosition().lng).indexOf(".");
        var lng = Math.round(point.lng * Math.pow(10, lngLength)) / Math.pow(10, lngLength);
        var latLength = ("" + e.target.getPosition().lat).length - 1 - ("" + e.target.getPosition().lat).indexOf(".");
        var lat = Math.round(point.lat * Math.pow(10, latLength)) / Math.pow(10, latLength);
        if (lng == e.target.getPosition().lng && lat == e.target.getPosition().lat)
            break;
    }
    //if (point.addr)
    //   createWindow(point.addr, point.lng, point.lat, point.created);
    //  else {
    createWindow("加载中，请稍候...", point.lng, point.lat, point.created);
    var gc = new BMap.Geocoder();
    var pt = new BMap.Point(point.lng, point.lat);
    gc.getLocation(pt, function(rs) {
        var addComp = rs.addressComponents;
        var addr = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
        var _pois = "";
        var pois = rs.surroundingPois;
        for (var i = 0; i < (pois.length > 3 ? 3 : pois.length); i++){
            //多个热点取第一个热点
             _pois += pois[i].title + "，";
             //_pois = pois[0].title + "，";
        }
        if (_pois.length > 0) {
            _pois = _pois.substring(0, _pois.length - 1);
            addr += "，" + _pois + "附近";
        }
        $("#spanAddr2").html(addr);
    });
    //  }
    e.target.openInfoWindow(infoWindow2);
}
/*
 * 判断地图有没有创建过maker点
 */
var uGetGPS_marker = false;

// 定位
function uGetGPSCallback(data) {
	 uGetGPS_flag = false;
    // if(map == undefined) {

    // } else {
    //     if(!data.success || data.type == 1) {
    //         map.removeControl(locateCtrl);
    //         map.addControl(locateCtrl);
    //     }
    // }
	/* map = new BMap.Map("location");
     
		
     map.addControl(new BMap.ScaleControl({
         anchor : BMAP_ANCHOR_BOTTOM_LEFT
     }));
     map.addControl(new BMap.NavigationControl());
*/
	  Device.createMap();
    if (data.success) {
    	//拿到所有终端
    	var devices = localStorage.getItem("devices");
    	//后台传入的终端
    	var device1 =localStorage.getItem(data.imei);
    	  var devices_imei=device1.split(",")[0];
  		var devices_name=device1.split(",")[1];
  		var devices_phone =device1.split(",")[2];
  		var devices_bat  =device1.split(",")[3];
  		var devices_lng  =device1.split(",")[4];
  		var devices_lat =device1.split(",")[5];
  		var devices_addr =device1.split(",")[6];
  		var devices_model =device1.split(",")[7];
  		var devices_self =device1.split(",")[8];
  		var devices_rfid=device1.split(",")[9];
        var devices_created = device1.split(",")[10];
  		var devices_password=device1.split(",")[11];
  		//当前终端
    	div_loc_showloading(devices_imei);
//    	console.log("data:lng="+data.lng+",lat="+data.lat+",created="+data.created);
//        
//        console.log("locstorage:lng="+devices_lng+",lat="+devices_lat+",created="+devices_created);
//        
//        console.log("lng equal="+(devices_lng==data.lng)+",lat equal="+(devices_lat==data.lat)+",created equal="+(devices_created==data.created));
        
        if(devices_lng==data.lng&&devices_lat==data.lat&&devices_created==data.created&& uGetGPS_marker==true){
            console.log("data==locstorage!!!");
            return;
        }
        

    	
        if (data.type == 0) {
        	var IMEI=localStorage.getItem("device").split(",")[0];
        	localStorage.setItem(devices_imei,devices_imei + "," + devices_name + "," + devices_phone + "," + data.bat + "," + data.lng + "," + data.lat + "," + data.addr + "," + devices_model + "," + devices_self + "," + devices_rfid+","+data.created+","+devices_password+","+data.loctype);
        	//var device2 =localStorage.getItem(devices_imei);
        //	Device.setDiviceByImei(devices_imei,device2);
        	if(data.imei==IMEI){
        		var device =localStorage.getItem("device").split(",");
        		
        		//localStorage_GPS(map,device);
        		//localStorage_GPS(device);
                // 清空地图
                map3.clearOverlays();
               /* if (infoWindow) {
                    infoWindow.close();
                }*/
                // 显示位置点
                var point = new BMap.Point(data.lng, data.lat);
                map3.centerAndZoom(point, 16);
         //  window.setTimeout(function(){ map.panTo(point); }, 500);

            var marker;
            if (data.loctype == 1)
                marker = new BMap.Marker(point, {
                    icon : new BMap.Icon("http://www.mingyitech.cn/mingyi/images/gps.png", new BMap.Size(36, 36), {
                                         anchor:new BMap.Size(18, 36),
                        infoWindowAnchor : new BMap.Size(10, 0)
                    })
                });
            else if (data.loctype == 4)
                marker = new BMap.Marker(point, {
                    icon : new BMap.Icon("http://www.mingyitech.cn/mingyi/images/wifi.png", new BMap.Size(36, 36), {
                                         anchor:new BMap.Size(18, 36),
                        infoWindowAnchor : new BMap.Size(10, 0)
                    })
                });
            else
                marker = new BMap.Marker(point, {
                    icon : new BMap.Icon("http://www.mingyitech.cn/mingyi/images/lbs.png", new BMap.Size(36, 36), {
                                         anchor:new BMap.Size(18, 36),
                        infoWindowAnchor : new BMap.Size(10, 0)
                    })
                });

                map3.addOverlay(marker);
                uGetGPS_marker=true;
                Device.isOnline = data.bat;
                //设备是否在线
            createWindow(data.addr, data.lng, data.lat, data.created, data.bat);
             console.log(data.created);
                marker.addEventListener("click", function() {
                 if (infoWindow) {
                                infoWindow.close();
                            }
                 console.log("createWindow2");
                 
                createWindow(data.addr, data.lng, data.lat, data.created, data.bat);
                    this.openInfoWindow(infoWindow);
                });
            marker.openInfoWindow(infoWindow);

        		
        		
        	}
        	if(uBandTerminal_panel){
                 $("#uBandTerminal_comm_id").hide();
        		localStorage_devicelist("#deviceList",devices);
        	}
        	
        } else if (data.type == 2) {
           if (data.reportTime) {
            } else {
                //收费网关时，单次定位启动跟踪30分钟
                //alert("实时跟踪设置成功。");
                $.afui.loadContent("#location", false, false, "none");
              //  localStorage.setItem(devices[0] + "_fol_start", new Date().getTime());
              //  localStorage.setItem(devices[0] + "_fol_duration", $("#duration").val() * 60);
            }
        }
    } else {
        if (data.error == 1) {
        	 uGetGPS_flag = false;
          map.clearOverlays();
               var lng1=Math.round(31.0417850000 * 1000000) / 1000000;
               var lat1=Math.round(112.2058430000 * 1000000) / 1000000;
                   console.log("lng:"+lng1);
                   console.log("lat:"+lat1);
               var point=new BMap.Point(lat1,lng1);
                   map.centerAndZoom(point, 16);
        } else if (data.error == 2){
        	 uGetGPS_flag = false;
            popuo("IMEI号不存在");
        }else{
        	 uGetGPS_flag = false;
        	 console.log("uGetGpS错误");
        	 var device =localStorage.getItem("device").split(",");
     		//localStorage_GPS(map,device);
     		localStorage_GPS(device);
        }
    }
}

// 跟踪
function follow() {
    var devices = localStorage.getItem("device").split(",");
    var duration = $("#duration").val() == "自定义" ? $("#duration-set").val() : $("#duration").val();
    var interval = $("#interval").val() == "自定义" ? $("#interval-set").val() : $("#interval").val();
    if (duration.trim() == "")
        popuo("自定义跟踪时长不能为空");
    else if (isNaN(parseInt(duration.trim())) || parseInt(duration.trim()) < 5 || parseInt(duration.trim()) > 10080)
        popuo("自定义跟踪时长必须为5~10080之间的数值");
    else if (interval.trim() == "")
        popuo("自定义跟踪间隔不能为空");
    else if (isNaN(parseInt(interval.trim())) || parseInt(interval.trim()) < 10 || parseInt(interval.trim()) > 3600)
        popuo("自定义跟踪间隔必须为10~3600之间的数值");
    else {
        $("#followBtn").attr("href", "javascript: void(0);");
        $("#followBtn").attr("class", "button block gray");
        sendCmd({
            c : 'uGetGPS',
            imei : devices[0],
            reportInterval : interval.trim(),
            reportDuration : duration.trim(),
            type : 2
        });
        Device.locationControl.data.showloading = true;
        Device.locationControl.data.flowtype = 'follow';
    }
}
//增加地图查询禁止缩放 -start-4.12
function getZoom (maxLng, minLng, maxLat, minLat) {
    var zoom = ["50","100","200","500","1000","2000","5000","10000","20000","25000","50000","100000","200000","500000","1000000","2000000"]//级别18到3。
    var pointA = new BMap.Point(maxLng,maxLat);  // 创建点坐标A
    var pointB = new BMap.Point(minLng,minLat);  // 创建点坐标B
    var distance = map2.getDistance(pointA,pointB).toFixed(1);  //获取两点距离,保留小数点后两位
    //    alert("getZoom:dis="+distance+",maxLng="+maxLng+",minLng="+minLng+",maxLat="+maxLat+",minLat="+minLat);
    for (var i = 0,zoomLen = zoom.length; i < zoomLen; i++) {
        if(zoom[i] - distance > 0){
            return 18-i+3;
        }
    };
}


function setZoom(points){
    if(points.length>1){
        var maxLng = points[0].lng;
        var minLng = points[0].lng;
        var maxLat = points[0].lat;
        var minLat = points[0].lat;
        var res;
        for (var i = points.length - 1; i >= 0; i--) {
            res = points[i];
            if(res.lng > maxLng) maxLng =res.lng;
            if(res.lng < minLng) minLng =res.lng;
            if(res.lat > maxLat) maxLat =res.lat;
            if(res.lat < minLat) minLat =res.lat;
        };
        var cenLng =(parseFloat(maxLng)+parseFloat(minLng))/2;
        var cenLat = (parseFloat(maxLat)+parseFloat(minLat))/2;
        var zoom = getZoom(maxLng, minLng, maxLat, minLat);
        //        alert("setZoom:zoom="+zoom);
        map2.centerAndZoom(new BMap.Point(cenLng,cenLat), zoom);
    }else{
        map2.centerAndZoom(new BMap.Point(points[0].lng,points[0].lat), 16);
    } 
}
//增加地图查询禁止缩放 -end-4.12

// 轨迹
function trackLogCallback(data) {
    if (data.success) {
    	stoper();
    	//setTimeout_showMask(unblockUI,30000);
    	unblockUI();
        track_mask_flag=false;
        // 进入定位界面
        $.afui.loadContent("#showTrack", false, false, "none");
        // 加载地图
        map2 = new BMap.Map("trackMap");
        map2.addControl(new BMap.ScaleControl({
            anchor : BMAP_ANCHOR_BOTTOM_LEFT
        }));
        var opts = {
        		offset: new BMap.Size(15, 68),
        		type: BMAP_NAVIGATION_CONTROL_SMALL,
        		anchor:BMAP_ANCHOR_BOTTOM_LEFT
        		} 
        map2.addControl(new BMap.NavigationControl(opts));
        
        var marker;
        points = new Array();
        markers = new Array();
        var _points = new Array();
        var datas = data.track;
        //增加地图查询禁止缩放
        setZoom(datas);
        for (var i = 0; i < datas.length; i++) {
            points.push(datas[i]);
            var point = new BMap.Point(datas[i].lng, datas[i].lat);
//            if (i == 0)
//                map2.centerAndZoom(point, 16);
            //如果轨迹查询只有一个点的时候，则显示E，
             if (datas.length == 1) {
                            marker = new BMap.Marker(point, {
                                icon : new BMap.Icon("http://api.map.baidu.com/img/markers.png", new BMap.Size(23, 25), {
                                    anchor : new BMap.Size(10, 25),
                                    infoWindowAnchor : new BMap.Size(10, 0),
                                    imageOffset : new BMap.Size(0, 0 - 4 * 25)
                                })
                            });
                        }
            else if (i == 0) {
                marker = new BMap.Marker(point, {
                    icon : new BMap.Icon("http://api.map.baidu.com/img/markers.png", new BMap.Size(23, 25), {
                        anchor : new BMap.Size(10, 25),
                        infoWindowAnchor : new BMap.Size(10, 0),
                        imageOffset : new BMap.Size(0, 0 - 1 * 25)
                    })
                });
            } else if (i == datas.length - 1) {
                marker = new BMap.Marker(point, {
                    icon : new BMap.Icon("http://api.map.baidu.com/img/markers.png", new BMap.Size(23, 25), {
                        anchor : new BMap.Size(10, 25),
                        infoWindowAnchor : new BMap.Size(10, 0),
                        imageOffset : new BMap.Size(0, 0 - 4 * 25)
                    })
                });
            } else {
                if (datas[i].loctype == 1)
                    marker = new BMap.Marker(point, {
                                             icon : new BMap.Icon("http://www.mingyitech.cn/mingyi/images/gps.png", new BMap.Size(36, 36),{anchor : new BMap.Size(18, 36),infoWindowAnchor : new BMap.Size(10, 0)})
                    });
                else if (datas[i].loctype == 4)
                    marker = new BMap.Marker(point, {
                                             icon : new BMap.Icon("http://www.mingyitech.cn/mingyi/images/wifi.png", new BMap.Size(36, 36),{anchor : new BMap.Size(18, 36),infoWindowAnchor : new BMap.Size(10, 0)})
                    });
                else
                    marker = new BMap.Marker(point,{
                        icon : new BMap.Icon("http://www.mingyitech.cn/mingyi/images/lbs.png", new BMap.Size(36, 36),{anchor : new BMap.Size(18, 36),infoWindowAnchor : new BMap.Size(10, 0)})
                    });
            }
            map2.addOverlay(marker);
            marker.addEventListener("click", function(e) {
                openWindow(e);
            });
            _points.push(point);
            markers.push(marker);
        }
        // 加载位置点及路线
        var polyline = new BMap.Polyline(_points, {
            strokeColor : "#0088d1",
            strokeWeight : 4,
            strokeOpacity : 0.8
        });
        map2.addOverlay(polyline);
    } else {
        track_mask_flag=false;
        if (data.error == 1){
            stoper();
            //Device.uBandTerminalCallback();
             popuo("暂无终端轨迹信息");
        }
        else if (data.error == 2){
        stoper();
        //Device.uBandTerminalCallback();
                 popuo("IMEI号不存在");
        }else{
        stoper();
        //Device.uBandTerminalCallback();
        }
    }
}

var pIndex = 0;
var trackIntval;
function playTrack() {
    if (infoWindow2 != undefined)
        infoWindow2.close();
    if ($("#play").attr("class") == "pl-pause") {
        $("#play").attr("class", "pl-play");
        clearInterval(trackIntval);
    } else {
        $("#play").attr("class", "pl-pause");
        if (pIndex == 0)
            $("#progress").animate({
                width : "0%",
                speed : "fast"
            });
        if (pIndex != points.length - 1)
            trackIntval = setInterval("play()", 1000);
        play();
    }
}

function play() {
    $("#progress").animate({
        width : parseInt((pIndex + 1) * 100 / points.length) + "%"
    });
    var _point = points[pIndex];
    var pt = new BMap.Point(_point.lng, _point.lat);
    
    var bs = map2.getBounds();   //获取可视区域
    var bssw = bs.getSouthWest();   //可视区域左下角
    var bsne = bs.getNorthEast();   //可视区域右上角
//    alert("当前地图可视范围是：" + bssw.lng + "," + bssw.lat + "到" + bsne.lng + "," + bsne.lat);
    if(!(pt.lng>bssw.lng&&pt.lng<bsne.lng&&pt.lat>bssw.lat&&pt.lat<bsne.lat))
       map2.setCenter(pt);
    if (pIndex > 0 && pIndex < points.length) {
        if (pIndex < points.length - 1) {
            markers[pIndex].setIcon(new BMap.Icon("http://api.map.baidu.com/img/markers.png", new BMap.Size(23, 25), {
                anchor : new BMap.Size(10, 25),
                infoWindowAnchor : new BMap.Size(10, 0),
                imageOffset : new BMap.Size(0, 0 - 2 * 25)
            }));
        }
        if (pIndex > 1) {
            if (_point.loctype == 1)
                markers[pIndex - 1].setIcon(new BMap.Icon("http://www.mingyitech.cn/mingyi/images/gps.png", new BMap.Size(36, 36),{anchor : new BMap.Size(18, 36),infoWindowAnchor : new BMap.Size(10, 0)}));

            else if (_point.loctype == 4)
                markers[pIndex - 1].setIcon(new BMap.Icon("http://www.mingyitech.cn/mingyi/images/wifi.png", new BMap.Size(36, 36),{anchor : new BMap.Size(18, 36),infoWindowAnchor : new BMap.Size(10, 0)}));
            else
                markers[pIndex - 1].setIcon(new BMap.Icon("http://www.mingyitech.cn/mingyi/images/lbs.png", new BMap.Size(36, 36),{anchor : new BMap.Size(18, 36),infoWindowAnchor : new BMap.Size(10, 0)}));
        }
    }
    pIndex++;
    if (pIndex == points.length) {
        pIndex = 0;
        $("#play").attr("class", "pl-play");
        clearInterval(trackIntval);
    }
}

function track() {
    if ($("#track-date").val().trim() == "")
        popuo("查询日期不能为空");
    else if ($("#track-begin").val().trim() == "")
        popuo("开始时间不能为空");
    else if ($("#track-end").val().trim() == "")
        popuo("结束时间不能为空");
    else {
        // 当前终端
        var device = localStorage.getItem("device");
        var devices = device.split(",");
          if(isConnected){
               	 sendCmd({
                        c : "trackLog",
                        fromTime : $("#track-date").val() + " " + $("#track-begin").val() + ":00",
                        toTime : $("#track-date").val() + " " + $("#track-end").val() + ":00",
                        imei : devices[0]
                    });
               	 Device.showMask_blockUI();
              track_mask_flag = true;
               	setTimeout_showMask(unblockUI,30000);
               	// Device.uBandTerminalCallback_30();
               }else{
               	popuo("连接超时，请检查网络设置");
               	socket.connect();
               }
    }
}
/*
//检测时间的方法
function checkTime(input, flag) {
            var pattern = /^(([0-1][0-9])|(2[0-3])|([0-9])):(([0-5][0-9])|([0-9]))$/;
            if(input.value != "" && (!pattern.test(input.value) || (flag && input.value == "00:00"))) {
                popuo("时间格式不正确");
                setTimeout(function(){input.focus();}, 1);
                return false;
            }
            if(input.value!=""){
                var HHMM = input.value.split(":");
                if(HHMM[0].length==1)
                  HHMM[0]="0"+HHMM[0];
                if(HHMM[1].length==1)
                  HHMM[1]="0"+HHMM[1];
                input.value=HHMM[0]+":"+HHMM[1];        
            }
            return true;
        }
//检测开始与结束时间        
 function checkForm() {
            if(!checkTime(document.getElementById("device.from1"), false))
                return false;
            else if(!checkTime(document.getElementById("device.to1"), true))
                return false;
            else if(!checkTime(document.getElementById("device.from2"), false))
                return false;
            else if(!checkTime(document.getElementById("device.to2"), true))
                return false;
            else if(!checkTime(document.getElementById("device.from3"), false))
                return false;
            else if(!checkTime(document.getElementById("device.to3"), true))
                return false;
            if(document.getElementById("device.from1").value != document.getElementById("device.to1").value && (document.getElementById("device.from1").value == "" || document.getElementById("device.to1").value == "")) {
                popuo("上午时间段未正确设置开始与结束时间");
                return false;
            }
            if(document.getElementById("device.from2").value != document.getElementById("device.to2").value && (document.getElementById("device.from2").value == "" || document.getElementById("device.to2").value == "")) {
                popuo("下午时间段未正确设置开始与结束时间");
                return false;
            }
            if(document.getElementById("device.from3").value != document.getElementById("device.to3").value && (document.getElementById("device.from3").value == "" || document.getElementById("device.to3").value == "")) {
                popuo("晚上时间段未正确设置开始与结束时间");
                return false;
            }
            return true;
        }
*/
//自身围栏的数量
var circlesLength_1=0;
//添加围栏标识
//var flag_addBtn2 = false;
// 围栏设置
function fencesettingCallback(data) {
    if (data.success) {
        if (data.type == 1) {
            if(isConnected){
                            $("#fencesetting_comm_id").hide();
                            //Device.uBandTerminalCallback();
                            stoper();
                           var html = "";
                           // $("#circleList").html("");
                           // var html = $("#circleList").html();
                            for (var i = 0; i < data.circles.length; i++) {
                                var circle = data.circles[i];
                               html += "<li class='swipe-reveal'>";
                                html += "	<div class='swipe-content' style='color: #666;' onclick=\"javascript: selectCircle('" + circle.id + "','" + circle.positionName + "'," + circle.positionAlarm + "," + circle.positionLng + "," + circle.positionLat + "," + circle.positionRadius + ");\">";
                                html += "       " + circle.positionName + "<br /><br />经纬度: &nbsp;" + circle.positionLng + ",&nbsp;" + circle.positionLat + "<br /><br />提醒: &nbsp;" + (circle.positionAlarm ? "开" : "关");
                                html += "		<div class='chevron'></div>";
                                html += "	</div>";
                                html += "	<div class='swipe-hidden'>";
                                html += "		<a class='button archive' style='padding-top: 54px;' onclick=\"javascript: removeCircle('" + circle.id + "');\">删除</a>";
                                html += "	</div>";
                                html += "</li>";
                            }
                            circlesLength_1=data.circles.length;
                            $("#circleList").html(html);
           }else{
                    if($("#circleList").text().length != 0){
                                        console.log("没网里面不为空："+$("#circleList").text().length );
                                         //Device.uBandTerminalCallback();
                                         stoper();
                                        $("#fencesetting_comm_id").hide();

                 }else{
                                         console.log("没网里面为空："+$("#circleList").text());
                                    //     Device.uBandTerminalCallback();
                                    //     $("#fencesetting_comm_id").show();
                                        $("#fencesetting_comm_id").hide();
                                         // 加载围栏列表
                                         sendCmd({
                                             c : "fencesetting",
                                             imei : localStorage.getItem("device").split(",")[0],
                                             type : 1
                                         });
                                         Device.showMask_blockUI();
                                         overTimeCallback_time_2("circleList","fencesetting_comm_id",10000);

                 }
            }

        } else if (data.type == 2) {
            //Device.uBandTerminalCallback();
            stoper();
          //新增围栏
          //  popuo("围栏信息保存成功");
            $.afui.goBack();
        }else if (data.type == 3) {
             //Device.uBandTerminalCallback();
             stoper();
             popuo("围栏信息保存成功");
             $.afui.goBack();
        }else if (data.type == 4) {
            //Device.uBandTerminalCallback();
            stoper();
            popuo("围栏删除成功");
            $("#circles").trigger('panelload');
        }
    } else {
        if (data.error == 1){
          //Device.uBandTerminalCallback();
          stoper();
          popuo("IMEI号不存在");
        }
        else if (data.error == 2) {
            $("#fencesetting_comm_id").hide();
            //Device.uBandTerminalCallback();
            stoper();
            $("#circleList").html("<div style='margin: 30px;'>暂无围栏设置<br /><br />可点击右上角“+”添加围栏信息</div>");
        }
        else if (data.error == 3){
                 //Device.uBandTerminalCallback();
                 stoper();
            popuo("系统异常，围栏不存在");
        }
        else if (data.error == 4){
                  //Device.uBandTerminalCallback();
                  stoper();
                 popuo("为了实现更精准的安全提醒，一公里内不建议设置多个安全区");
        }
        else if(data.error == 5){
                //Device.uBandTerminalCallback();
                stoper();

                popuo("围栏已满");
        }
    }
    if (data.type == 2 || data.type == 3) {
        $("#circleBtn").attr("href", "javascript:saveCircle();");
        $("#circleBtn").attr("class", "button block blue");
    }
}

function addDevice1(){
	 if(isConnected){
		 if(deviceLength<10){
		 console.log("deviceLength11111:"+deviceLength);
			 $.afui.loadContent("#addDevice", false, false, "none");
		 }else{
		  console.log("deviceLength222222:"+deviceLength);
				popuo("终端已满");
		 }
     }else{
          	popuo("连接超时，请检查网络设置");
          	socket.connect();
          }

}

function addCircle() {
    if(isConnected){
    		 if(circlesLength_1<circlesLength){
    			    $("#circle-id").val("");
    			    $("#circle-name").val("");
    			    $("#circle-notify").prop("checked", false);
    			    $("#lng").val("");
    			    $("#lat").val("");
    			    $("#radius").val(300);
    			    $.afui.loadContent("#circleDetail", false, false, "none");
    		 }else{
    				popuo("围栏已满");
    		 }
    }else{
             popuo("连接超时，请检查网络设置");
             socket.connect();
    }
}

function selectCircle(id, name, alarm, lng, lat, radius) {
    $("#circle-id").val(id);
    $("#circle-name").val(name);
    $("#circle-notify").prop("checked", alarm);
    $("#lng").val(lng);
    $("#lat").val(lat);
    $("#radius").val(radius);
    $.afui.loadContent("#circleDetail", false, false, "none");
}

function saveCircle() {
    if ($("#circle-name").val().trim() == "")
        popuo("围栏名称不能为空");
    else if ($("#lng").val().trim() == "" || $("#lat").val().trim() == "")
        popuo("经纬度不能为空");
    else {
        if(isConnected){
                $("#circleBtn").attr("href", "javascript: void(0);");
                $("#circleBtn").attr("class", "button block gray");
                var device = localStorage.getItem("device");
                var devices = device.split(",");
               	sendCmd({
                       c : "fencesetting",
                       id : $("#circle-id").val(),
                       positionName : $("#circle-name").val(),
                       positionAlarm : $("#circle-notify").prop("checked"),
                       positionLng : $("#lng").val(),
                       positionLat : $("#lat").val(),
                       positionRadius : $("#radius").val(),
                       imei : devices[0],
                       type : $("#circle-id").val() == "" ? 2 : 3
                   });
                 	 Device.showMask_blockUI_2();
                 	// Device.uBandTerminalCallback_10();
                 	overTimeCallback_time("circleBtn","saveCircle",10000);
                 }else{
                 	popuo("连接超时，请检查网络设置");
                 	socket.connect();
                 }
         }
    }

function removeCircle(id) {
    deletePopuo("删除围栏",id,removec);
 }


function removec(id){
	  	  var device = localStorage.getItem("device");
	      var devices = device.split(",");
	      if(isConnected){
	             sendCmd({
	                         c : "fencesetting",
	                         id : id,
	                         imei : devices[0],
	                         type : 4
	             });
	             Device.showMask_blockUI_3();
	             //Device.uBandTerminalCallback_10();
	             setTimeout_showMask(unblockUI,10000);
	      }else{
                popuo("连接超时，请检查网络设置");
                socket.connect();
          }
}


// 通知
function uGetNotifyCallback(data) {
    if (data.success) {
        // 去除新消息数字提示
        $.afui.removeBadge("#noticeLink");
        var _data = localStorage.getItem("loginUser").split(",");
        var infoData = localStorage.getItem(_data[0]);
       // var receive = true;
        if (infoData != null) {
            var info = infoData.split(",-,");
            //receive = info[0] == 'true';
        }
        // 是否开启消息
      /*  if (!receive) {
            $("#noticeMore").css("display", "none");
            $("#noticeList").html("<div style='margin: 30px;'>通知信息已关闭。<br />如需查看，请至设置菜单打开此功能。</div>");
     } else {*/
            var notices = data.notices;
            $("#noticeMore").css("display", "block");
            if (notices.length < pageSize)
                $("#noticeMore").html("没有更多记录了");
            else
                $("#noticeMore").html("加载更多");
            if (notices.length == 0) {
                if (pageIndex == 1) {
                    $("#noticeMore").css("display", "none");
                    $("#noticeList").html("<div style='margin: 30px;'>暂无通知信息。</div>");
                }
            } else {
                var html = $("#noticeList").html();
                for (var i = 0; i < notices.length; i++) {
                    var notice = notices[i];
                    html += "<li>";
                    if (notice.checked)
                        html += "	<span style='display:block; font-size:14px; font-weight:bold;word-break:break-all;'>" + notice.description + "</span>";
                    else
                        html += "	<span style='display:block; font-size:14px;word-break:break-all;'>" + notice.description + "</span>";
                    //通知消息地址
                    //if (notice.addr)
                    //      html += "	<br /><span style='display:block; margin-top:-10px; font-size:12px;'>位置：" + notice.addr + "</span>";
                    html += "	<br /><span style='display:block; margin-top:-10px; font-size:12px;'>" + notice.created + "</span>";
                    html += "</li>";
                    //后台类型传输
                    //popuo(notice.type);
                }
                $("#noticeList").html(html);
            }
      //  }
    } else
        popuo("IMEI号不存在");
}

//铃声控制标识
var flag_message = false;

// 有新消息通知
function onMessage(data) {
    flag_message = true;
    sendCmd({
        c : "uGetNewMessage",
        imei : data.imei
    });
    console.log("我用了onMessage这个方法");

}

//时时检测新消息返回
function uGetNewMessageCallback(data) {
    var _data = localStorage.getItem("loginUser").split(",");
    var infoData = localStorage.getItem(_data[0]);
  /*  var receive = true;
    var sound = true;
    var vibrate = true;
    if (infoData != null) {
        var info = infoData.split(",-,");
        receive = info[0] == 'true';
        sound = info[1] == 'true';
        vibrate = info[2] == 'true';
    }*/
    if (data.success) {
        // 是否开启消息
      //  if (receive) {
            // 当前终端是否选中
            var selected = false;
            if (localStorage.getItem("device") != null)
                selected = data.imei == localStorage.getItem("device").split(",")[0];
            if (data.messages.length > 0) {
                if (selected) {
                    $.afui.updateBadge("#noticeLink", data.messages.length, "tr", "red");
                    //如果在通知界面#notice页面就直接刷新一遍
                    //panelload

                }
                // 发送通知栏消息
                // data.messages
                // 响铃
                if (flag_message) {
                //    if (sound)
                        navigator.notification.beep(1);
                    // 震动
              //      if (vibrate)
                        navigator.notification.vibrate(1000);
                    //description,addr
                 /*   for (var i = 0; i < data.messages.length; i++) {
                        var message = data.messages[i];
                        var msg = ["宝贝呢", message.description];
                        window.plugins.notify.send(msg, function() {
                            popuo("成功");
                        }, function(msg) {
                            popuo(msg || "失败");
                        });
                    }*/
                }
            } else {
                if (selected)
                    $.afui.removeBadge("#noticeLink");
            }
     //   }
    } else {
        popuo("IMEI号不存在");
    }
}

// 时时检测新消息
function uGetNewMessage() {
    flag_message = false;
    var _data = localStorage.getItem("loginUser").split(",");
    var infoData = localStorage.getItem(_data[0]);
   // var receive = true;
    if (infoData != null) {
        var info = infoData.split(",-,");
    //    receive = info[0] == 'true';
    }
    // 是否开启消息
  //  if (receive) {
        sendCmd({
            c : "uGetNewMessage",
            imei : localStorage.getItem("device").split(",")[0]
        });
 //   }

}

// 上课隐身
function classHiddingCallback(data) {
    if (data.success) {
        if (data.type == 1) {
        //Device.uBandTerminalCallback();
        stoper();
            $("#hid-switch").prop("checked", data.onOff);
            if (data.onOff) {
                $("#hid-area").css("display", "block");
                for (var i = 0; i < 3; i++) {
                    $("#hid" + (i == 0 ? "" : i + 1) + "-begin1").val(data.settings[i].from1);
                    $("#hid" + (i == 0 ? "" : i + 1) + "-end1").val(data.settings[i].to1);
                    $("#hid" + (i == 0 ? "" : i + 1) + "-begin2").val(data.settings[i].from2);
                    $("#hid" + (i == 0 ? "" : i + 1) + "-end2").val(data.settings[i].to2);
                    $("#hid" + (i == 0 ? "" : i + 1) + "-begin3").val(data.settings[i].from3);
                    $("#hid" + (i == 0 ? "" : i + 1) + "-end3").val(data.settings[i].to3);
                    $("#hid" + (i == 0 ? "" : i + 1) + "-begin4").val(data.settings[i].from4);
                    $("#hid" + (i == 0 ? "" : i + 1) + "-end4").val(data.settings[i].to4);
                    $("#hid" + (i == 0 ? "" : i + 1) + "-begin5").val(data.settings[i].from5);
                    $("#hid" + (i == 0 ? "" : i + 1) + "-end5").val(data.settings[i].to5);
                    $("#hid" + (i == 0 ? "" : i + 1) + "-begin6").val(data.settings[i].from6);
                    $("#hid" + (i == 0 ? "" : i + 1) + "-end6").val(data.settings[i].to6);
                }
            } else {
                $("#hid-area").css("display", "none");
            }
        } else{
         //Device.uBandTerminalCallback();
         stoper();
        popuo("上课隐身设置保存成功");
        $.afui.goBack();
        $("#deviceSetting").trigger('panelbeforeload');
         //alert("上课隐身设置保存成功。");
        }
    } else {
        //Device.uBandTerminalCallback();
        stoper();
        popuo("IMEI号不存在");
    }
}

function checkFlagTrueOrFalse(){
    if(checkFlag == 0 ){
                 popuo("开始时间不能大于等于结束时间");
             return ;
    }else if(checkFlag == 1 ){
                popuo("结束时间不能为空");
             return;
    }else if(checkFlag == 2){
                popuo("开始时间不能为空");
             return;
    }

}

function hidding() {
    checkFlag = 0;
    function checkVaild(pre, num) {
        for (var i = 1; i <= num; i++) {
            var begin = $("#" + pre + "-begin" + i).val();
            var end = $("#" + pre + "-end" + i).val();
            if (begin.length !== 0) {
                 if(end.length !== 0){
                    if (begin >= end) {
                         return false;
                        }
                 }else{
                    checkFlag=1;
                    return false;
                 }
            }else{
                if(end.length !== 0){
                     checkFlag=2;
                     return false;
                }
            }
        }
        return true;
    }
    var device = localStorage.getItem("device");
    var devices = device.split(",");
    var model = devices[7];
    var longpoll = model.length >= 19 ? parseInt(model.substring(18, 19)) : 0;
    if (longpoll == 0) {
        // 添加校验
        if (!checkVaild("hid", 3)) {
            checkFlagTrueOrFalse();
           return;
        }

    if(isConnected){
                   	 sendCmd({
                                 c : "classHidding",
                                 imei : localStorage.getItem("device").split(",")[0],
                                 hiddingOnOff : $("#hid-switch").prop("checked"),
                                 type : 2,
                                 settings : [{
                                     from1 : $("#hid-begin1").val(),
                                     to1 : $("#hid-end1").val(),
                                     from2 : $("#hid-begin2").val(),
                                     to2 : $("#hid-end2").val(),
                                     from3 : $("#hid-begin3").val(),
                                     to3 : $("#hid-end3").val(),
                                     day : 1
                                 }]
                             });
                   	 Device.showMask_blockUI_2();
                   	// Device.uBandTerminalCallback_10();
                   	setTimeout_showMask(unblockUI,10000);
                   }else{
                   	popuo("连接超时，请检查网络设置");
                   	socket.connect();
                   }
    } else {
        // 添加校验

        if (!checkVaild("hid", 6)) {
            checkFlagTrueOrFalse();
            return;
        }
        if (!checkVaild("hid2", 6)) {
            checkFlagTrueOrFalse();
            return;
        }
        if (!checkVaild("hid3", 6)) {
            checkFlagTrueOrFalse();
            return;
        }
        if(isConnected){
                       sendCmd({
                                   c : "classHidding",
                                   imei : localStorage.getItem("device").split(",")[0],
                                   hiddingOnOff : $("#hid-switch").prop("checked"),
                                   type : 2,
                                   settings : [{
                                       from1 : $("#hid-begin1").val(),
                                       to1 : $("#hid-end1").val(),
                                       from2 : $("#hid-begin2").val(),
                                       to2 : $("#hid-end2").val(),
                                       from3 : $("#hid-begin3").val(),
                                       to3 : $("#hid-end3").val(),
                                       from4 : $("#hid-begin4").val(),
                                       to4 : $("#hid-end4").val(),
                                       from5 : $("#hid-begin5").val(),
                                       to5 : $("#hid-end5").val(),
                                       from6 : $("#hid-begin6").val(),
                                       to6 : $("#hid-end6").val(),
                                       day : 1
                                   }, {
                                       from1 : $("#hid2-begin1").val(),
                                       to1 : $("#hid2-end1").val(),
                                       from2 : $("#hid2-begin2").val(),
                                       to2 : $("#hid2-end2").val(),
                                       from3 : $("#hid2-begin3").val(),
                                       to3 : $("#hid2-end3").val(),
                                       from4 : $("#hid2-begin4").val(),
                                       to4 : $("#hid2-end4").val(),
                                       from5 : $("#hid2-begin5").val(),
                                       to5 : $("#hid2-end5").val(),
                                       from6 : $("#hid2-begin6").val(),
                                       to6 : $("#hid2-end6").val(),
                                       day : 2
                                   }, {
                                       from1 : $("#hid3-begin1").val(),
                                       to1 : $("#hid3-end1").val(),
                                       from2 : $("#hid3-begin2").val(),
                                       to2 : $("#hid3-end2").val(),
                                       from3 : $("#hid3-begin3").val(),
                                       to3 : $("#hid3-end3").val(),
                                       from4 : $("#hid3-begin4").val(),
                                       to4 : $("#hid3-end4").val(),
                                       from5 : $("#hid3-begin5").val(),
                                       to5 : $("#hid3-end5").val(),
                                       from6 : $("#hid3-begin6").val(),
                                       to6 : $("#hid3-end6").val(),
                                       day : 3
                                   }]
                               });
                       	 Device.showMask_blockUI_2();
                       	// Device.uBandTerminalCallback_10();
                       	setTimeout_showMask(unblockUI,10000);
                       }else{
                       	popuo("连接超时，请检查网络设置");
                       	socket.connect();
                       }
    }
}

// 定时跟踪
function followingSettingCallback(data) {
    if (data.success) {
        if (data.type == 1) {
        //Device.uBandTerminalCallback();
        stoper();
            $("#follow-switch").prop("checked", data.onOff);
            if (data.onOff) {
                $("#follow-area").css("display", "block");
                $("#followingContent").css("display", "block");
                $("#followingInterval").val(data.interval);
                for (var i = 0; i < 3; i++) {
                    $("#follow" + (i == 0 ? "" : i + 1) + "-begin1").val(data.settings[i].from1);
                    $("#follow" + (i == 0 ? "" : i + 1) + "-end1").val(data.settings[i].to1);
                    $("#follow" + (i == 0 ? "" : i + 1) + "-begin2").val(data.settings[i].from2);
                    $("#follow" + (i == 0 ? "" : i + 1) + "-end2").val(data.settings[i].to2);
                    $("#follow" + (i == 0 ? "" : i + 1) + "-begin3").val(data.settings[i].from3);
                    $("#follow" + (i == 0 ? "" : i + 1) + "-end3").val(data.settings[i].to3);
                    $("#follow" + (i == 0 ? "" : i + 1) + "-begin4").val(data.settings[i].from4);
                    $("#follow" + (i == 0 ? "" : i + 1) + "-end4").val(data.settings[i].to4);
                    $("#follow" + (i == 0 ? "" : i + 1) + "-begin5").val(data.settings[i].from5);
                    $("#follow" + (i == 0 ? "" : i + 1) + "-end5").val(data.settings[i].to5);
                    $("#follow" + (i == 0 ? "" : i + 1) + "-begin6").val(data.settings[i].from6);
                    $("#follow" + (i == 0 ? "" : i + 1) + "-end6").val(data.settings[i].to6);
                }
            } else {
                $("#follow-area").css("display", "none");
                $("#followingContent").css("display", "none");
            }
        } else{
         //Device.uBandTerminalCallback();
         stoper();
        popuo("定时跟踪设置保存成功");
        /*$.afui.goBack();
        $("#deviceSetting").trigger('panelbeforeload');*/
      // alert("定时跟踪设置保存成功。");
        }
    } else {
        //Device.uBandTerminalCallback();
        stoper();
        popuo("IMEI号不存在");
    }
}

var checkFlag = 0;
function followingSetting() {
    checkFlag = 0;
    function checkVaild() {
        for (var i = 0; i < 3; i++) {
            var begin1 = $("#follow" + (i == 0 ? "" : i + 1) + "-begin1").val();
            var end1 = $("#follow" + (i == 0 ? "" : i + 1) + "-end1").val();
            if (begin1.length !== 0) {
                 if(end1.length !== 0){
                      if (begin1 >= end1) {
                       return false;
                      }
                 }else{
                     checkFlag=1;
                     return false;
                 }
            }else{
                 if(end1.length !== 0){
                    checkFlag=2;
                    return false;
                 }
            }
            var begin2 = $("#follow" + (i == 0 ? "" : i + 1) + "-begin2").val();
            var end2 = $("#follow" + (i == 0 ? "" : i + 1) + "-end2").val();
            if (begin2.length !== 0) {
                  if(end2.length !== 0){
                         if (begin2 >= end2) {
                                   return false;
                         }
                  }else{
                        checkFlag=1;
                        return false;
                  }
            }else{
                  if(end2.length !== 0){
                         checkFlag= 2;
                         return false;
                  }
            }
             var begin3 = $("#follow" + (i == 0 ? "" : i + 1) + "-begin3").val();
             var end3 = $("#follow" + (i == 0 ? "" : i + 1) + "-end3").val();
            if (begin3.length !== 0) {
                  if(end3.length !== 0){
                        if (begin3 >= end3) {
                              return false;
                        }
                  }else{
                         checkFlag= 1;
                         return false;
                  }
            }else{
                 if(end3.length !== 0){
                         checkFlag= 2;
                         return false;
                 }
            }
             var begin4 = $("#follow" + (i == 0 ? "" : i + 1) + "-begin4").val();
             var end4 = $("#follow" + (i == 0 ? "" : i + 1) + "-end4").val();
            if (begin4.length !== 0) {
                  if(end4.length !== 0){
                       if (begin4 >= end4) {
                        return false;
                       }
                  }else{
                       checkFlag=1;
                        return false;
                  }
            }else{
                  if(end4.length !== 0){
                    checkFlag=2;
                    return false;
                  }
            }
        }
        return true;
    }
    if (!checkVaild()) {
         checkFlagTrueOrFalse();
        return;
    }

if(isConnected){
               	  sendCmd({
                         c : "followingSetting",
                         imei : localStorage.getItem("device").split(",")[0],
                         followingOnOff : $("#follow-switch").prop("checked"),
                         interval : $("#followingInterval").val(),
                         type : 2,
                         settings : [{
                             from1 : $("#follow-begin1").val(),
                             to1 : $("#follow-end1").val(),
                             from2 : $("#follow-begin2").val(),
                             to2 : $("#follow-end2").val(),
                             from3 : $("#follow-begin3").val(),
                             to3 : $("#follow-end3").val(),
                             from4 : $("#follow-begin4").val(),
                             to4 : $("#follow-end4").val(),
                             from5 : $("#follow-begin5").val(),
                             to5 : $("#follow-end5").val(),
                             from6 : $("#follow-begin6").val(),
                             to6 : $("#follow-end6").val(),
                             day : 1
                         }, {
                             from1 : $("#follow2-begin1").val(),
                             to1 : $("#follow2-end1").val(),
                             from2 : $("#follow2-begin2").val(),
                             to2 : $("#follow2-end2").val(),
                             from3 : $("#follow2-begin3").val(),
                             to3 : $("#follow2-end3").val(),
                             from4 : $("#follow2-begin4").val(),
                             to4 : $("#follow2-end4").val(),
                             from5 : $("#follow2-begin5").val(),
                             to5 : $("#follow2-end5").val(),
                             from6 : $("#follow2-begin6").val(),
                             to6 : $("#follow2-end6").val(),
                             day : 2
                         }, {
                             from1 : $("#follow3-begin1").val(),
                             to1 : $("#follow3-end1").val(),
                             from2 : $("#follow3-begin2").val(),
                             to2 : $("#follow3-end2").val(),
                             from3 : $("#follow3-begin3").val(),
                             to3 : $("#follow3-end3").val(),
                             from4 : $("#follow3-begin4").val(),
                             to4 : $("#follow3-end4").val(),
                             from5 : $("#follow3-begin5").val(),
                             to5 : $("#follow3-end5").val(),
                             from6 : $("#follow3-begin6").val(),
                             to6 : $("#follow3-end6").val(),
                             day : 3
                         }]
                     });
               	 Device.showMask_blockUI_2();
               	 //Device.uBandTerminalCallback_10();
               	 setTimeout_showMask(unblockUI,10000);
               }else{
               	popuo("连接超时，请检查网络设置");
               	socket.connect();
               }
    }

// 闹钟
function alarmsettingCallback(data) {
    if (data.success) {
        if (data.type == 1) {
             //Device.uBandTerminalCallback();
             stoper();
            $("#alarm-switch").prop("checked", data.onOff);
            if (data.onOff) {
                $("#alarm-area").css("display", "block");
                for (var i = 0; i < 3; i++) {
                    $("#alarm" + (i == 0 ? "" : i + 1) + "-begin1").val(data.settings[i].from1);
                    $("#alarm" + (i == 0 ? "" : i + 1) + "-begin2").val(data.settings[i].from2);
                    $("#alarm" + (i == 0 ? "" : i + 1) + "-begin3").val(data.settings[i].from3);
                    $("#alarm" + (i == 0 ? "" : i + 1) + "-begin4").val(data.settings[i].from4);
                    $("#alarm" + (i == 0 ? "" : i + 1) + "-begin5").val(data.settings[i].from5);
                    $("#alarm" + (i == 0 ? "" : i + 1) + "-begin6").val(data.settings[i].from6);
                }
            } else {
                $("#alarm-area").css("display", "none");
            }
        } else{
         //Device.uBandTerminalCallback();
         stoper();
         popuo("闹钟设置保存成功");
         $.afui.goBack();
         $("#deviceSetting").trigger('panelbeforeload');
        }
    } else {
        //Device.uBandTerminalCallback();
        stoper();
        popuo("IMEI号不存在");
    }
}

function alarmsetting() {
 if(isConnected){
               	 sendCmd({
                         c : "alarmsetting",
                         imei : localStorage.getItem("device").split(",")[0],
                         alarmOnOff : $("#alarm-switch").prop("checked"),
                         type : 3,
                         settings : [{
                             from1 : $("#alarm-begin1").val(),
                             from2 : $("#alarm-begin2").val(),
                             from3 : $("#alarm-begin3").val(),
                             from4 : $("#alarm-begin4").val(),
                             from5 : $("#alarm-begin5").val(),
                             from6 : $("#alarm-begin6").val(),
                             day : 1
                         }, {
                             from1 : $("#alarm2-begin1").val(),
                             from2 : $("#alarm2-begin2").val(),
                             from3 : $("#alarm2-begin3").val(),
                             from4 : $("#alarm2-begin4").val(),
                             from5 : $("#alarm2-begin5").val(),
                             from6 : $("#alarm2-begin6").val(),
                             day : 2
                         }, {
                             from1 : $("#alarm3-begin1").val(),
                             from2 : $("#alarm3-begin2").val(),
                             from3 : $("#alarm3-begin3").val(),
                             from4 : $("#alarm3-begin4").val(),
                             from5 : $("#alarm3-begin5").val(),
                             from6 : $("#alarm3-begin6").val(),
                             day : 3
                         }]
                     });
               	 Device.showMask_blockUI_2();
               	// Device.uBandTerminalCallback_10();
               	setTimeout_showMask(unblockUI,10000);
               }else{
               	popuo("连接超时，请检查网络设置");
               	socket.connect();
               }
        }

// 监听
function monitorCallback(data) {
    if (data.success)
        popuo("已通知终端启动监听，请等待终端回拔");
    else
        popuo("系统异常，请重试");
}

function monitor() {
   // 用户登录号码 alert(_data[1]); 用户注册号码
  	var _data = localStorage.getItem("loginUser").split(",");
  	var monitorNum=_data[1];
  	var re = new RegExp("^[0-9]*$");
      // 验证是否为数字格式 ,要求字数为2-20;
  	layer.open({
  		  title:['确定要启用监听功能吗',
  		         'color:#3E4041; font-weight:600;padding-left:27px;padding-right:27px;'
  		         ],
  		  shadeClose: false,
  		  //shade:false,
  		  btn: ['确认', '取消'],
  	    content:  " <input id='monitorID' type='text' maxlength='20'  value="+_data[1]+" />",
  	    yes: function(index){
  	    	var monitorNum_1= $("#monitorID").val().trim();
  	    	    if (monitorNum_1 != null || monitorNum_1 != "") {
  	    	        if (monitorNum_1.length < 2 || monitorNum_1.length > 20) {
  	    	        	console.log("号码位数限制：2~20");
  	    	        	popuo("号码位数限制：2~20");
  	    	        } else if (!re.test(monitorNum_1)) {
  	    	        	popuo("无效号码");
  	    	        	console.log("无效号码");
  	    	        } else if (re.test(monitorNum_1)) {
  	    	        	console.log("我执行命令")
  	    	            sendCmd({
  	    	                c : "monitor",
  	    	                monitorNum : monitorNum_1,
  	    	                imei : localStorage.getItem("device").split(",")[0],
  	    	            });
  	    	        }
  	    	        }
  	    	    layer.close(index);
  	    }, no: function(){
  	    	popuo("已取消监听");
  	    }
  	});
/*
    // 用户登录号码 alert(_data[1]); 用户注册号码
    var _data = localStorage.getItem("loginUser").split(",");
    var monitorNum = window.prompt("确定要启用监听功能吗？", _data[1]);
    // window.confirm("确定要启用监听功能吗？")
    var re2 = new RegExp("^[A-Za-z0-9]+$");
    //验证由数字和26个英文字母组成的字符串
    var re = new RegExp("^[0-9]*$");
    // 验证是否为数字格式 ,要求字数为2-20;
    if (monitorNum != null || monitorNum != "") {
        if (monitorNum.length < 2 || monitorNum.length > 20) {
            popuo("号码位数限制：2~20");
        } else if (!re.test(monitorNum)) {
            popuo("无效号码");
        } else if (re.test(monitorNum)) {
            //alert(monitorNum);
            sendCmd({
                c : "monitor",
                monitorNum : monitorNum,
                imei : localStorage.getItem("device").split(",")[0],
            });
        }
    } else {
        popuo("已取消监听！");
    }*/
}

// 定时开关机
function alarmPowerOnOffCallback(data) {
    if (data.success) {
        if (data.type == 1) {
            $("#power-begin").val(data.alarmPowerOnTime);
            $("#power-end").val(data.alarmPowerOffTime)
        } else
            popuo("定时开关机设置成功");
    } else
        popuo("系统异常，请重试");
}

function alarmPowerOnOff() {
    sendCmd({
        c : "alarmPowerOnOff",
        type : 2,
        imei : localStorage.getItem("device").split(",")[0],
        alarmPowerOnTime : $("#power-begin").val(),
        alarmPowerOffTime : $("#power-end").val()
    });
}

// 考勤查询
function uSchoolRecordCallback(data) {
    if (data.success) {

        if (data.attendances.length < pageSize){
         $("#attdanceMore").html("没有更多记录了");
        }
        else{
         $("#attdanceMore").html("加载更多");
        }
        if (data.attendances.length == 0) {
            if (pageIndex == 1){
            //Device.uBandTerminalCallback();
            stoper();
            popuo("暂无相关考勤记录信息");
            /*$.afui.goBack();
            $("#deviceSetting").trigger('panelbeforeload');*/
            }
        } else {
            //Device.uBandTerminalCallback();
            stoper();
            var html = $("#attdanceUl").html();
            for (var i = 0; i < data.attendances.length; i++) {
                var attdance = data.attendances[i];
                html += "<li>";
                html += attdance.created.substring(0, 10) + "&nbsp;&nbsp;&nbsp;";
                if (attdance.status == 0 || attdance.status == 2)
                    html += "进校";
                else if (attdance.status == 1 || attdance.status == 3)
                    html += "离校";
                else if (attdance.status == 4 || attdance.status == 5)
                    html += "未知";
                else
                    html += "异常";
                html += "<div style='float: right; margin-right: 10px;'>";
                html += attdance.created.substring(11, 16);
                html += "</div>";
                html += "</li>";
            }
            $("#attdanceUl").html(html);
            // 进入考勤显示界面
            $.afui.loadContent("#attdances", false, false, "none");
        }
    } else {
        if (data.error == 1){
        //Device.uBandTerminalCallback();
        stoper();
            popuo("IMEI号不存在");
        }
        else if (data.error == 2){
        //Device.uBandTerminalCallback();
        stoper();
         popuo("RFID号不存在");
        }
    }
}

function uSchoolRecord() {
    if ($("#attdance-begin").val().trim() == "")
        popuo("开始日期不能为空");
    else if ($("#attdance-end").val().trim() == "")
        popuo("结束日期不能为空");
    else {
        pageIndex = 1;
        $("#attdanceUl").html("");
        $("#attdanceMore").html("加载更多");
         if(isConnected){
                       	 sendCmd({
                                     c : "uSchoolRecord",
                                     imei : localStorage.getItem("device").split(",")[0],
                                     start : $("#attdance-begin").val() + " 00:00:00",
                                     end : $("#attdance-end").val() + " 23:59:59",
                                     pageIndex : pageIndex,
                                     pageSize : pageSize
                                 });
                       	 Device.showMask_blockUI();
                       	 //Device.uBandTerminalCallback_10();
                       	 setTimeout_showMask(unblockUI,10000);
                       }else{
                       	popuo("连接超时，请检查网络设置");
                       	socket.connect();
                       }
    }
}

// 加载更多
function addMore(type) {
    if ($("#attdanceMore").html() == "加载更多") {
        if (type == 1) {
            // 考勤查询
            pageIndex++;
            sendCmd({
                c : "uSchoolRecord",
                imei : localStorage.getItem("device").split(",")[0],
                start : $("#attdance-begin").val() + " 00:00:00",
                end : $("#attdance-end").val() + " 23:59:59",
                pageIndex : pageIndex,
                pageSize : pageSize
            });
        } }
        if($("#noticeMore").html() == "加载更多"){
          if (type != 1)  {
            // 加载通知
            pageIndex++;
            sendCmd({
                c : "uGetNotify",
                imei : localStorage.getItem("device").split(",")[0],
                pageIndex : pageIndex,
                pageSize : pageSize
            });
        }
    }
}

// 有新位置点上报
function uReportCallback(data) {
    if (data.success) {
        // 保存最后上报点时间
      //  localStorage.setItem(data.imei + "_loc_report", new Date().getTime());
        // 判断是否需要更新地图位置
       // if (localStorage.getItem("device").split(",")[0] == data.imei) {
        	
            sendCmd({
                c : 'uGetGPS',
                imei : data.imei
            });
        	
      //  }
    }
}

function popuo(_content){
	  layer.open({
		    content:_content,
		    className:'popuo',
		    style: 'background-color:#666666; color:#C0C0C0; border:none;',
		    fixed:false,
		    top: (document.documentElement.clientHeight)/2+200,
		    shade:false,
		    time: 2
		});
}

function deletePopuo(title,id,_function){
	 layer.open({
		 	title:[title,
		 	 'color:#3E4041; font-weight:600;padding-left:64px;font-size:19px'],
		    content: '',
		    btn: ['确认', '取消'],
		    shadeClose: false,
		    yes: function(index){
		    	_function(id);
	                         layer.close(index);
		    }, no: function(){
		    	console.log("取消"+title);
		    }
		});
}
// 超时处理
function overTimeCallback_time(id,javascript1,time){
	setTimeout(function () {
	    $.afui.unblockUI();
	     $.afui.hideMask();
               console.log("hideMask-----1");
	     $("#"+id).attr("href", "javascript:"+ javascript1+"()");
	     $("#"+id).attr("class", "button block blue");
	 }, time);
}
function overTimeCallback_time(id,javascript1,time,javascript1_parameter){
	setTimeout(function () {
	    $.afui.unblockUI();
	     $.afui.hideMask();
               console.log("hideMask-----2");
	     $("#"+id).attr("href", "javascript:"+ javascript1+"("+javascript1_parameter+")");
	     $("#"+id).attr("class", "button block blue");
	 }, time);
}

//自发加载数据的超时处理
function overTimeCallback_time_2(id,id2,time){
	setTimeout(function () {
               if(!track_mask_flag){
	    $.afui.unblockUI();
	     $.afui.hideMask();
               console.log("hideMask-----3");
               }
	     uBandTerminal_flag = false;
	     if($("#"+id).text().length != 0){
                                     //Device.uBandTerminalCallback();
                                     stoper();
                                     $("#"+id2).hide();
         }else{
                                     //Device.uBandTerminalCallback();
                                     stoper();
                                     $("#"+id2).show();
         }

	 }, time);
}

//发送ugetGPS超时处理
function overTimeCallback_time_3(flag1,time){
	setTimeout(function () {
		flag1 = false;
	 }, time);
}
function unblockUI(){
    console.log("---unblockUI!!!!");
    $.afui.unblockUI();
     $.afui.hideMask();
}

function setTimeout_showMask(unblockUI,time){
    if(ctime!=null){
        console.log("setTimeout_showMask:"+ctime);
        clearTimeout(ctime);
    }
    ctime = setTimeout(function(){
                       $.afui.unblockUI();
                       $.afui.hideMask();
                       track_mask_flag=false},time);
}

function stoper() {
    console.log("---stoper()!!!");
	clearTimeout(ctime);
	ctime=null;
	if(!track_mask_flag){
	$.afui.unblockUI();
    $.afui.hideMask();
    }
	}

////////////////////add by mll begin 2015-12-22

var Device = {
    isLongLink : function(imei) {
        var dev = this.getDiviceByImei(imei);
        if (dev != null || dev != undefined) {
            var model = dev.model;
            if (model != '' && model.length >= 19) {
                //19位：表示是短连接还是长链接，0短连接   1长连接
                if (model.substring(18, 19) == '1') {
                    return true;
                }
            }
        }
        return false;
    },
    isFreeMsgGate : function(imei) {
        var dev = this.getDiviceByImei(imei);
        if (dev != null || dev != undefined) {
            var model = dev.model;
            if (model != '' && model.length >= 24) {
                //24位：是否是收费的短信网关，0表示收费的短信网关，1表示免费的短信网关，此标志位只有短链接才起作用
                if (model.substring(23, 24) == '1') {
                    return true;
                }
            }
        }
        return false;
    },

    showMask_blockUI_2:function(data){
    	$.afui.blockUI(.1);
    	$.afui.showMask_2("请稍后...");
       },
     showMask_blockUI_1:function(data){
    	$.afui.blockUI(.1);
    	$.afui.showMask_2("正在登录...");
       },
    showMask_blockUI_3:function(data){
    	$.afui.blockUI(.1);
    	$.afui.showMask_2("正在删除，请稍后...");
       },
   showMask_blockUI:function(data){
	$.afui.blockUI(.1);
	 $.afui.showMask_2("正在加载，请稍候...");
        },


   uBandTerminalCallback_10 : function (data) {
	    setTimeout(function () {
	             $.afui.unblockUI()
	              $.afui.hideMask();
                   console.log("hideMask-----4");
          }, 10000);
        },
    uBandTerminalCallback_30 : function (data) {
    	  setTimeout(function () {
                 $.afui.unblockUI()
                  $.afui.hideMask();
                     console.log("hideMask-----5");
              }, 30000);
          
         },
    uBandTerminalCallback : function (data) {
                     if(!track_mask_flag){
                     $.afui.unblockUI();
                      $.afui.hideMask();
                     console.log("hideMask-----6");
                     }
         },
   
    getDiviceByImei : function(imei) {
        return JSON.parse(localStorage.getItem("device-" + imei) || "{}");
    },
    setDiviceByImei : function(imei, device) {
        localStorage.setItem("device-" + imei, JSON.stringify(device));
    },
    //获取当前设备的名称
    currentName : function() {
        // 显示当前终端
        var device = localStorage.getItem("device");
        var devices = device.split(",");
        return devices[1] || "";
    },
    getCurrentModel : function() {
        var dev = this.getCurrentDevice();
        return dev.model;
    },
    // 获取当前终端
    getCurrentDevice : function() {
        var device = localStorage.getItem("device") || '';
        var dev = this.getDiviceByImei(device.split(",")[0]);
        return dev;
    },

    setDeviceLocTime : function(imei, time) {
        localStorage.setItem("device-loctime-" + imei, time);
    },
    getDeviceLocTime : function(imei) {
        var time = localStorage.getItem("device-loctime-" + imei);
        console.log(time+","+imei);
        return time || 0;
    },

    //25位：是否是数据卡（不支持通话及短信，只支持数据流量），0 表示不是数据卡，1 表示是数据卡
    isIoTCard : function() {
        var dev = this.getCurrentDevice();
        var model = dev.model || "";
        if (model.length >= 25) {
            return model.substring(24, 25) == '1';
        }
        return false;
    },

    //收费短信网关和免费的短信网关可以根据数据词典来区分 第24位
    //是否是收费的短信网关，1表示不收费的短信网关，0表示收费的短信网关，此标志位只有短链接才起作用
    getMsgType : function(model) {
        if (model != '' && model.length >= 24) {
            //收费短信网关和免费的短信网关可以根据数据词典来区分 第24位
            return model.substring(23, 24);

        } else {
            return "";
        }
    },
    //19位：表示是短连接还是长链接，0短连接   1长连接
    getLinkType : function(model) {
        if (model != '' && model.length >= 19) {
            //收费短信网关和免费的短信网关可以根据数据词典来区分 第24位
            return model.substring(18, 19);

        } else {
            return "";
        }
    },

    // 设备是否在线,需要取uGetGPS接口中的bat字段表示,0表示离线
    isOnline : 0,

    // 创建地图
    createMap : function() {
        // 如果没有创建地图,则创建地图,创建地图时,一定要在div显示后再创建,否则页面显示不正确
     if (!Device.map) {
    	  console.log("Device.map:"+Device.map);
            //////////////
            //include_JS("BmapId","http://api.map.baidu.com/api?v=2.0&ak=DCRGgn4Ow9sUHfGfsOveLCey");
            map3 = new BMap.Map("location");
            map3.addControl(new BMap.ScaleControl({
                anchor : BMAP_ANCHOR_BOTTOM_LEFT
            }));
            var opts = {
            		offset: new BMap.Size(15, 68),
            		type: BMAP_NAVIGATION_CONTROL_SMALL,
            		anchor:BMAP_ANCHOR_BOTTOM_LEFT
            		}  
            map3.addControl(new BMap.NavigationControl(opts)
            );
      
            // 定义一个控件类，即function
            function LocateControl() {
                // 设置默认停靠位置和偏移量
                this.defaultAnchor = BMAP_ANCHOR_BOTTOM_RIGHT;
                this.defaultOffset = new BMap.Size(10, 50);
            }


            LocateControl.prototype = new BMap.Control();
            LocateControl.prototype.initialize = function(map) {
                var div = $($("#location-tools-script").html())[0];
                map.getContainer().appendChild(div);

                new Vue(Device.locationControl);

                return div;
            }
            locateCtrl = new LocateControl();
            // 添加到地图当中
            map3.addControl(locateCtrl);
           Device.map = map3;
         window.map = map3;
            //////////////
     }
    },

    //设备定位相关的内容
    location : {
        el : "#location",
        ready : function() {
            //定位
            $('#location').on('panelbeforeload', function(e) {
                // 控制按钮显示
                $.afui.setBackButtonVisibility(false);
                $("#backBtn").show();
               // $.afui.setTitle(Device.currentName());
            $.afui.setTitle("定位");
            if(!uGetGPS_flag){
            	 IMEI1=localStorage.getItem("device").split(",")[0];
            	 console.log("IMEI1:"+IMEI1);
           sendCmd({
        		c : "uGetGPS",
        		imei :localStorage.getItem("device").split(",")[0]
        	});
           
          console.log(IMEI1);
           uGetGPS_flag = true;
           overTimeCallback_time_3(uGetGPS_flag,10000);
            }else{
            	var device =localStorage.getItem("device").split(",");
            	console.log("location");
        		//localStorage_GPS(map,device);
        		localStorage_GPS(device);
            	console.log(device);
            }
            });
            $('#location').on('panelload', function(e) {
                // 控制按钮显示
                $.afui.setBackButtonVisibility(false);
                $("#backBtn").show();
                // 显示当前终端
                $.afui.setTitle(Device.currentName());
                if (Device.isIoTCard()) {
                    $('#dialLink').hide();
                }
                IMEI1=localStorage.getItem("device").split(",")[0];
              /*  sendCmd({
            		c : "uGetGPS",
            		imei :localStorage.getItem("device").split(",")[0]
            	});*/
                
                
            });
        }
    },

    // 自定义地图控件处理方法
    locationControl : {
        el : "#location-tools",
        ready : function() {

        },
        data : {
            showloading : false,
            flowtype : '',//定位类型,单次定位为:loc,跟踪为:follow
        },
        //计算属性
        computed : {
            //单次定位
            spinnerMargin : function() {
                if (this.isShowFollow) {
                    return this.flowtype == 'follow' ? '-47px' : '-147px'
                } else {
                    return "-100px";
                }

            },
            // 跟踪是否显示
            isShowFollow : function() {
                var model = Device.getCurrentModel();
                var msgType = Device.getMsgType(model);
                //0表示收费的短信网关，1表示免费的短信网关，
                msgType = msgType == '' ? "0" : msgType;
                // 如果msgType为空,则默认为收费的短信网关,否则,请后台将model长度补齐到24位
                var linkType = Device.getLinkType(model);
                //0短连接   1长连接
                linkType = linkType == '' ? "0" : linkType;
                //如果linkType为空,则默认为短链接
                //如果是收费的短信网关，并且是短链接，则屏蔽此功能,msgType + linkType != '00'
                //现在更改成所有都不显示
                return false;
            },
        },

        // 事件方法
        methods : {
            callLocate : function() {

                var model = Device.getCurrentModel();
                var msgType = Device.getMsgType(model);
                //0表示收费的短信网关，1表示免费的短信网关，
                msgType = msgType == '' ? "0" : msgType;
                // 如果msgType为空,则默认为收费的短信网关,否则,请后台将model长度补齐到24位
                var linkType = Device.getLinkType(model);
                //0短连接   1长连接
                linkType = linkType == '' ? "0" : linkType;
                //如果linkType为空,则默认为短链接
        if(isConnected){
               	 switch (msgType + linkType) {
                                 // 如果是收费的短信网关，并且是短链接，点击后，要提示客户：“开启30分钟的位置上报”，开启后，30分钟内不允许再次点击
                                 case '00': {
                                     //果终端离线，则不能操作，提示客户“终端离线，无法操作”；
                                     if (Device.isOnline == 0) {
                                        /* $.afui.toast({
                                             message : "终端[" + Device.currentName() + "]离线，无法操作",
                                             position : "bc",
                                             autoClose : true, //have to click the message to close
                                             type : "warning",
                                             delay : 3000
                                         });*/
                                         popuo("终端[" + Device.currentName() + "]离线，无法操作");
                                     } else {
                                         var imei = Device.getCurrentDevice().imei || '';
                                         if (new Date().getTime() - Device.getDeviceLocTime(imei) < 30 * 60 * 1000) {
                                             //单次定位跟踪状态
                                             /* $.afui.toast({
                                              message: "已经开启30分钟的位置上报后，30分钟内不允许再次点击！",
                                              position: "bc",
                                              autoClose: false, //have to click the message to close
                                              type: "warning",
                                              });*/

                                         } else if (this.flowtype == 'follow') {
                                             //跟踪状态
                                             /*   $.afui.toast({
                                              message: "终端已处于跟踪状态，最新位置点信息已实时上报。",
                                              position: "bc",
                                              autoClose: true, //have to click the message to close
                                              type: "warning",
                                              delay: 3000
                                              });*/
                                         } else {
                                             /* $.afui.popup({
                                             title : "开启30分钟的位置上报",
                                             message : "开启30分钟的位置上报后，30分钟内不允许再次点击。",
                                             cancelText : "不开启",
                                             cancelCallback : function() {
                                             console.log("cancelled");
                                             },
                                             doneText : "开启",
                                             doneCallback : function() {*/
                                             // sendCmd({ c: 'uGetGPS', imei: imei, type: 1 });
                                             //1）如果是收费的短信网关，并且是短链接，点击后，开启30分钟的跟踪，间隔是300秒，并且需要提示客户“开启三十分钟位置上报”，下发的接口同临时跟踪的接口
                                        	/*if(Device.locationControl.data.showloading ) {
                                        		Device.locationControl.data.showloading = false;
                                        	}*/
                                             sendCmd({
                                                 c : 'uGetGPS',
                                                 imei : imei,
                                                 reportInterval : 300,
                                                 reportDuration : 30,
                                                 type : 2
                                             });
                                             // 添加发送指令时间
                                             Device.setDeviceLocTime(imei, new Date().getTime());
                                             Device.locationControl.data.showloading = true;
                                             setTimeout(function() {
                                                 Device.locationControl.data.showloading = false;
                                             }, 1800 * 1000)
                                             Device.locationControl.data.flowtype = 'loc'
                                             /*Device.setDeviceLocTime(imei, new Date().getTime());
                                             this.showloading = true;
                                             setTimeout( function() {
                                                 this.showloading = false;
                                             }.bind(this), 1800 * 1000)
                                             this.flowtype = 'loc'*/
                                             /*},
                                              cancelOnly : false
                                              });*/
                                         }

                                     }

                                     break;
                                 }//case '10':

                                 case '10':
                                 case '11':
                                 case '01': 
                                 default: {
                                     var imei = Device.getCurrentDevice().imei || '';
                                     if (new Date().getTime() - Device.getDeviceLocTime(imei) < 18 * 1000) {

                                     } else {
                                         sendCmd({
                                             c : 'uGetGPS',
                                             imei : imei,
                                             type : 1
                                         });
                                         // 添加发送指令时间
                                         Device.setDeviceLocTime(imei, new Date().getTime());
                                         this.showloading = true;
                                         setTimeout( function() {
                                             this.showloading = false;
                                         }.bind(this), 90 * 1000)
                                         this.flowtype = 'loc';
                                     }
                                 break;    
                                 }

                                 } // switch(msgType+linkType)
               }else{
                	popuo("连接超时，请检查网络设置");
                	socket.connect();
               }
            }, // callLocate: function()
            callQueryTrack : function callQueryTrack() {
                $.afui.loadContent("#queryTrack", false, false, "none");
            },
            callFollowing : function callFollowing() {
                if (this.flowtype != 'follow') {
                    $.afui.loadContent("#followSetting", false, false, "none");
                } else {
                    var imei = Device.getCurrentDevice().imei || '';
                    $.afui.popup({
                        title : "实时跟踪",
                        message : "已经开启实时跟踪,是否关闭?",
                        cancelText : "不关闭",
                        cancelCallback : function() {
                            console.log("cancelled");
                        },
                        doneText : "关闭",
                        doneCallback : function() {
                            sendCmd({
                                c : 'uGetGPS',
                                imei : imei,
                                reportInterval : 0,
                                reportDuration : 0,
                                reportTime : 999999999999,
                                type : 2
                            });
                            Device.locationControl.data.showloading = false;
                            Device.locationControl.data.flowtype = ''
                        },
                        cancelOnly : false
                    });
                }
            }
        } //methods
    }
}

///////////////////add by mll end 2015-12-22

////////////////// add by mll begin 2015-12-23

////////////////// add by mll end 2015-12-23
